package com.naiterui.ehp.bs.search.service.impl;

import com.naiterui.common.redis.RedisUtil;
import com.naiterui.ehp.bs.search.repository.mysql.ISearchDrStandardDiagnosisRepository;
import com.naiterui.ehp.bs.search.service.IThirdDiagnosisService;
import com.naiterui.ehp.bs.search.utils.PropertyValueConstants;
import com.naiterui.ehp.bs.search.vo.ThirdDiagnosisSyncVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author guoyongxiang
 * @date 2018/11/19 17:14
 * @since 1.0.0
 */
@Service
public class SearchThirdDiagnosisServiceImpl implements IThirdDiagnosisService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SearchThirdDiagnosisServiceImpl.class);

    @Autowired
    private ISearchDrStandardDiagnosisRepository standardDiagnosisRepository;

    @Override
    public Integer sync(List<ThirdDiagnosisSyncVO> vo) {
        // 查询标准诊断
        boolean hasCache = RedisUtil.keyOps().existsKey(PropertyValueConstants.REDIS_DIAGNOSIS_STANDARD_KEY);
        if (!hasCache) {
            // 缓存失效查询数据库
            List<String> standardNames = standardDiagnosisRepository.getAllNames();
            String[] arr = standardNames.toArray(new String[standardNames.size()]);
            RedisUtil.setOps().sadd(PropertyValueConstants.REDIS_DIAGNOSIS_STANDARD_KEY, arr);
            // 该KEY使用频率为每天晚上固定时间点循环调用，总量约18000每1000条一次，因此设置缓存30分钟
            RedisUtil.keyOps().expire(PropertyValueConstants.REDIS_DIAGNOSIS_STANDARD_KEY, 1800);
            LOGGER.info("刷新标准诊断缓存 size:{}", standardNames.size());
        }

        // 从缓存中获取标准诊断列表
        Set<String> diagnosisStandardSet = RedisUtil.setOps().smembers(PropertyValueConstants.REDIS_DIAGNOSIS_STANDARD_KEY);
        Set<String> emptySku = new HashSet<>();
        // 有效sku
        int effectiveSku = 0;
        // 遍历药品关键字缓存交集后的记录
        for (ThirdDiagnosisSyncVO sku : vo) {
            if (sku.getIndicationKeywords() == null && sku.getDisease() == null) {
                continue;
            }
            // 替换中文逗号
            String keywords = sku.getIndicationKeywords() == null ? "" : sku.getIndicationKeywords().replaceAll("，", ",");
            String disease = sku.getDisease() == null ? "" : sku.getDisease().replaceAll("，", ",");
            String[] keywordsArr = (keywords + "," + disease).split(",");
            Set<String> keywordSet = new HashSet<>();
            for (String k : keywordsArr) {
                keywordSet.add(k);
            }
            keywordSet.retainAll(diagnosisStandardSet);
            if (keywordSet.isEmpty()) {
                emptySku.add(sku.getSkuId() + "");
            } else {
                RedisUtil.hashOps().hsetObject(PropertyValueConstants.REDIS_MEDIC_DIAGNOSIS_KEY, sku.getSkuId() + "", keywordSet);
                effectiveSku++;
            }

        }
        // 删除空记录的药品key
        if (emptySku.size() > 0) {
            Long delCount = RedisUtil.hashOps()
                    .hdelObject(PropertyValueConstants.REDIS_MEDIC_DIAGNOSIS_KEY, emptySku.toArray(new String[emptySku.size()]));
            LOGGER.info("传入sku数量:{}, 删除无效sku:{}, 实际删除:{}", vo.size(), emptySku.size(), delCount);
        }
        return effectiveSku;
    }
}
